package com.chen.config;

import jakarta.annotation.PostConstruct;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQACJConfig implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback {
    // 第二部,  设置
    @Autowired
    private RabbitTemplate rabbitTemplate;
    // 创建对象完成后,自动调用这个方法
    @PostConstruct
    public void init() {
        // 把我们自定义的方法设置进去
        rabbitTemplate.setConfirmCallback(this);  // 路由器
        rabbitTemplate.setReturnsCallback(this); //队列
    }


    // 第一步先重写两个回掉方法
    /**
     *  消息发送成功、失败发送到交换机时,调用的方法
     correlationData – correlation data for the callback.
     ack – true for ack, false for nack(no acknowledge)
     cause – An optional cause, for nack, when available, otherwise null.
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        //soutp+enter 快速打印参数
        System.out.println("correlationData = " + correlationData + ", ack = " + ack + ", cause = " + cause);
    }

    /**
     * 发送到队列失败,  调用这个方法
     * @param returned the returned message and metadata.
     */

    @Override
    public void returnedMessage(ReturnedMessage returned) {
        System.out.println("消息主体: " + new String(returned.getMessage().getBody()));
        System.out.println("应答码: " + returned.getReplyCode());
        System.out.println("描述：" + returned.getReplyText());
        System.out.println("消息使用的交换器 exchange : " + returned.getExchange());
        System.out.println("消息使用的路由键 routing : " + returned.getRoutingKey());
    }
}
